<template>
  <div class="mian-container">
    <div class="search">
      <el-input
        v-model="productName"
        placeholder="请输入产品名称查询"
        style="width: 200px"
        size="small"
      ></el-input>
      <el-button
        type="info"
        plain
        style="margin-left: 10px"
        size="small"
        @click="search"
        >查询</el-button
      >
      <el-button
        type="warning"
        plain
        style="margin-left: 10px"
        size="small"
        @click="reset"
        >重置</el-button
      >
    </div>

    <div class="operation">
      <el-button type="primary" plain size="small" @click="handleAdd"
        >新增</el-button
      >
      <el-button type="danger" plain size="small" @click="delBatch"
        >批量删除</el-button
      >
    </div>

    <div class="table">
      <el-table
        :data="tableData"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column prop="productImage" label="农产品图片">
          <template v-slot="scope">
            <el-image
              style="width: 80px; height: 60px; border-radius: 5px"
              :src="scope.row.productImage"
              fit="fill"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="productName"
          label="农产品名称"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="description"
          label="农产品描述"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column prop="label" label="标签" width="220">
          <template v-slot="scope">
            <el-tag
              type="success"
              style="margin-right: 10px"
              v-for="label in scope.row.label"
              v-show="label.name"
              >{{ label.name }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" sortable > </el-table-column>
        <el-table-column prop="quantity" label="数量" sortable > </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template v-slot="scope">
            <el-button
              plain
              type="primary"
              size="mini"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              plain
              type="danger"
              size="mini"
              @click="handleDelete(scope.row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNo"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          :total="total"
          layout="total,prev,pager,next"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      title="农产品管理"
      :visible.sync="showVisiable"
      width="50%"
      :close-on-click-modal="false"
      destory-on-close
    >
      <el-form
        label-width="100px"
        :model="editForm"
        ref="formRef"
        :rules="rules"
      >
        <el-form-item prop="imageList" label="农产品图片">
          <el-upload
            ref="uploadfiles"
            class="upload-demo"
            action="http://localhost:3000/files/upload"
            list-type="picture-card"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :file-list="editForm.imageList"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg文件，且不超过5MB
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item prop="productName" label="农产品名称">
          <el-input
            v-model="editForm.productName"
            auto-complete="off"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item prop="description" label="农产品描述">
          <el-input
            type="textarea"
            v-model="editForm.description"
            auto-complete="off"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item prop="label" label="标签">
          <el-input
            placeholder="标签一"
            v-model="editForm.label[0].name"
            auto-complete="off"
            size="small"
          ></el-input>
          <el-input
            placeholder="标签二"
            v-model="editForm.label[1].name"
            auto-complete="off"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item prop="price" label="价格">
          <el-input
            type="number"
            v-model="editForm.price"
            @blur="editForm.price = parseFloat(editForm.price)"
            auto-complete="off"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item prop="quantity" label="数量">
          <el-input
            type="number"
            v-model="editForm.quantity"
            @blur="editForm.quantity = parseInt(editForm.quantity)"
            auto-complete="off"
            size="small"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="imgUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
import {
  reqCharProductInfo,
  addCharProduct,
  delBatchCharProduct,
  delCharProduct,
  updateCharProduct,
  searchCharProduct,
} from "@/api/charProduct.js";
export default {
  name: "characteristicProduct",
  data() {
    // 校验规则
    let validatePrice = (rule, value, callback) => {
      if (value === undefined) {
        callback(new Error("请输入价格"));
      } else if (value <= 0) {
        callback(new Error("价格必须大于0元"));
      } else {
        callback();
      }
    };
    let validateQuantity = (rule, value, callback) => {
      if (value === undefined) {
        callback(new Error("请输入数量"));
      } else if (value <= 0) {
        callback(new Error("数量必须大于0"));
      } else {
        callback();
      }
    };
    return {
      tableData: [],
      productName: "",
      editForm: {
        productName: "",
        productImage: "",
        description: "",
        label: [{name:""}, {name:""}],
        price: undefined,
        quantity: undefined,
        imageList:[]
      },
      delBatchData: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      showVisiable: false,
      dialogVisible: false,
      imgUrl: "",
      rules: {
        productName: [
          { required: true, message: "请输入农产品名称", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入农产品描述", trigger: "blur" },
        ],
        price: [{ required: true, validator: validatePrice, trigger: "blur" }],
        quantity: [
          { required: true, validator: validateQuantity, trigger: "blur" },
        ],
      },
      fileList: [],
    };
  },
  methods: {
    // 点击确定保存按钮的回调
    save() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          this.editForm.productImage = this.editForm.imageList[0].response.url;
          // 发请求
          if (!this.editForm._id) {
            let result = await addCharProduct(this.editForm);
            if (result.code == 200) {
              this.$message.success(result.msg);
              this.showVisiable = false;
              this.pageNo = 1;
              this.getcharProductList(this.pageNo, this.pageSize);
              this.$refs.uploadfiles.clearFiles();
            } else {
              this.$message.error(result.msg);
            }
          } else {
            let result = await updateCharProduct(this.editForm);
            if (result.code == 200) {
              this.$message.success(result.msg);
              this.showVisiable = false;
              this.pageNo = 1;
              this.getcharProductList(this.pageNo, this.pageSize);
              this.$refs.uploadfiles.clearFiles();
            } else {
              this.$message.error(result.msg);
            }
          }
        }
      });
    },

    // 点击取消按钮的回调
    cancle() {
      this.$refs["formRef"].resetFields();
      this.$refs.uploadfiles.clearFiles();
      this.showVisiable = false;
    },

    // 查询回调
    async search() {
      let result = await searchCharProduct(this.productName);
      if (result.code == 200) {
        this.$message.success(result.msg);
        this.tableData = result.data;
        this.total = result.total
      } else {
        this.$message.error(result.msg);
      }
    },

    // 点击重置按钮清空搜索框的回调
    reset() {
      this.productName = "";
      this.pageNo = 1;
      this.getcharProductList(this.pageNo, this.pageSize);
    },

    // 新增回调
    handleAdd() {
      this.editForm = {
        productName: "",
        productImage: "",
        description: "",
        label: [{name:""}, {name:""}],
        price: undefined,
        quantity: undefined,
      };
      this.showVisiable = true;
    },

    // 点击删除按钮的回调
    async handleDelete(_id) {
      let data = { _id };
      let result = await delCharProduct(data);
      if (result.code == 200) {
        this.$message.success(result.msg);
        this.pageNo = 1;
        this.getcharProductList(this.pageNo, this.pageSize);
      } else {
        this.$message.error(result.msg);
      }
    },

    // 批量删除回调
    async delBatch() {
      let result = await delBatchCharProduct(this.delBatchData);
      if (result.code == 200) {
        this.$message.success(result.msg);
        this.pageNo = 1;
        this.getcharProductList(this.pageNo, this.pageSize);
      } else {
        this.$message.error(result.msg);
      }
    },

    // 点击修改按钮的回调
    handleEdit(row) {
      this.editForm = JSON.parse(JSON.stringify(row));
      this.showVisiable = true;
    },

    // 获取农产品列表
    async getcharProductList(pageNo, pageSize) {
      let result = await reqCharProductInfo(pageNo, pageSize);
      if (result.code == 200) {
        this.tableData = result.data;
        this.tableData.forEach(item => {
          item.imageList.forEach(i => {
            i.url = i.response.url
          })
        })
        this.total = result.total;
      } else {
        this.$message.error(result.msg);
      }
    },

    // 勾选回调
    handleSelectionChange(val) {
      let arr = val.map((item) => {
        return item._id;
      });
      this.delBatchData = arr;
    },
    // 分页器
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getcharProductList(this.pageNo, this.pageSize);
    },
    handleSizeChange(val) {
      this.pageNo = val;
      this.getcharProductList(this.pageNo, this.pageSize);
    },
    // 图片上传成功的回调
    handleSuccess(res, file,fileList) {
      this.editForm.imageList = fileList;
    },

    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 5MB!");
      }
      return isJPG && isLt2M;
    },
    handleRemove(file, fileList) {
      this.editForm.imageList = fileList;
    },
    handlePreview(file) {
      this.imgUrl = file.response.url;
      this.dialogVisible = true;
    },
  },
  mounted() {
    this.getcharProductList(this.pageNo, this.pageSize);
  },
  watch: {
    productName: function (newVal, oldVal) {
      if (newVal === "") {
        this.pageNo = 1;
        this.getcharProductList(this.pageNo, this.pageSize);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.main-container {
  .search {
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
  }
  .category {
    margin-top: 5px;
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
  }
  .operation {
    margin-top: 5px;
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
  }
  .table {
    margin-top: 5px;
    padding: 15px 10px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}
</style>
